/*
 * rsidlib: Open source library for PKI functions on Serbian eID (GNU LGPLv3)
 * Copyright (C) 2011 Aleksandar Nikolic
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version
 * 3.0 as published by the Free Software Foundation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, see
 * http://www.gnu.org/licenses/.
 */

package rsidlib;

import java.util.Arrays;
import java.util.HashMap;

/**
 * Pomocne metode za rukovanje karticom
 * @author Aleksandar Nikolic
 *
 */
public class RSIDUtils {
	
    public static String int2Hex(final int i)
    {
    	return bytes2Hex(new byte[] {
    			(byte)(i >>> 24),
                (byte)(i >>> 16),
                (byte)(i >>> 8),
                (byte) i});
    }
    
    static String bytes2Hex(final byte[] bytes)
    {
        String result = "", sep = "";
        for(byte b:bytes)
        {
        	if(sep == "" && b == 0x00) continue;
        	
        	result += sep + String.format("%02X", b);
        	sep = ":";
        }
        return result;
    }   
    
    static String bytes2UTFString(final byte[] bytes)
    {
    	if(bytes == null) return "";
    	
    	try {
    		return new String(bytes, "UTF-8");
    	}
    	catch(Exception e)
    	{
    		return new String(bytes);
    	}
    }
    
    static HashMap<Integer, byte[]> parseTLV(byte[] bytes)
    {
    	HashMap<Integer, byte[]> out = new HashMap<Integer, byte[]>();

    	// [fld] [06] [len] [00] [len bytes of data] | [fld] [06] ...
    	
    	int i = 0;
    	while(i+3 < bytes.length)
    	{
    		// is there a new tag?
    		if(bytes[i+1] != 0x06 || bytes[i+3] != 0x00 || i+4+bytes[i+2] >= bytes.length) break;

			out.put(new Integer(bytes[i]), Arrays.copyOfRange(bytes, i+4, i+4+bytes[i+2]));

    		i += 4+bytes[i+2];    		
    	}
    	
    	return out;
    }
}
